 //
//  MainViewController.swift
//  我的微博
//
//  Created by Creator on 15/10/8.
//  Copyright © 2015年 Creator. All rights reserved.
//

import UIKit

class MainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        addChildViewControllers()
    }
    
    override func viewDidLayoutSubviews() {
        setupComposeButton()
    }
    
    // 按钮位置
    private func setupComposeButton() {
    
        let w = tabBar.bounds.width / CGFloat(childViewControllers.count)
        let rect = CGRect(x: 0, y: 0, width: w, height: tabBar.bounds.height)
        
        composedButton.frame = CGRectOffset(rect, 2 * w, 0)
    
    }
    
    // MARK: - 运行循环监听到的事件后，向VC发送消息，执行动态方法 不能设置privatr
    func clickComposeButton() {
//        print(__FUNCTION__)
        
        // 根据用户是否登录 来决定是否显示发布微博的界面
        let vc  = UserAccount.userLogon ? ComposeViewController() : OAuthViewController()
        
        let nav = UINavigationController(rootViewController: vc)
        
        // 此方法就是mode出来的界面
        presentViewController(nav, animated: true, completion: nil)
    }
   
    private func addChildViewControllers() {
    
        addChildViewController(HomeTableViewController(), title:"首页", imageName:"tabbar_home")
        addChildViewController(MessageTableViewController(), title:"消息", imageName:"tabbar_message_center")
        addChildViewController(UIViewController())
        
        addChildViewController(DiscoverTableViewController(), title:"发现", imageName:"tabbar_discover")
        addChildViewController(ProfileTableViewController(), title:"我", imageName:"tabbar_profile")
        
        
    }
        
    

    private func addChildViewController(vc: UIViewController, title: String, imageName: String)
    {

        let nvc = UINavigationController(rootViewController: vc)
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        addChildViewController(nvc)
        
    }
    
    // 懒加载
    lazy private var composedButton: UIButton = {
    
     /// 自定义按钮 ----> 登录注册
        let btn = UIButton()

        btn.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        btn.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        self.tabBar.addSubview(btn)
        btn.addTarget(self, action: "clickComposeButton", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    
    }()
    

}
